package com.company.cloud.work.modules.mgr.service.impl;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.company.cloud.common.bean.BaseClientResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.cloud.work.modules.base.entity.WorkCommentInfo;
import com.company.cloud.work.modules.base.service.WorkCommentInfoService;
import com.company.cloud.work.modules.cache.models.WorkCommentModel;
import com.company.cloud.work.modules.cache.utils.CrmWorkChangeUtils;
import com.company.cloud.work.modules.mgr.controller.req.WorkCommentSaveParam;
import com.company.cloud.work.modules.mgr.service.WorkCommentMgrService;

@Service
public class WorkCommentMgrServiceImpl implements WorkCommentMgrService{

	
	@Autowired
	private WorkCommentInfoService workCommentInfoService;
	@Autowired
	private UserRemoteService userRemoteService;

	@Override
	public WorkCommentModel save(WorkCommentSaveParam params, LoginSimpleUserInfo userInfo) {
		ValidatorUtils.validate(params);
		
		
		WorkCommentInfo entity=workCommentInfoService.getOne(new QueryWrapper<WorkCommentInfo>()
				.eq("rows_state", EnabledEnum.ENABLED.getCode())
				.eq("company_no", userInfo.getCompanyNo())
				.eq("user_id", userInfo.getId())
				.eq("rel_biz_type", params.getRelBizType())
				.eq("rel_biz_id", params.getRelBizId())
				);
		
		if(entity==null) {
			entity=new WorkCommentInfo();
			entity.setCompanyNo(userInfo.getCompanyNo());
			entity.setUserId(userInfo.getId());
			entity.setRelBizType(params.getRelBizType());
			entity.setRelBizId(params.getRelBizId());
			entity.setComment(params.getComment());
			entity.setCommentDate(LocalDateTime.now());
			entity.addCreateParam(userInfo);
			entity.addEditParam(userInfo);
			workCommentInfoService.save(entity);
		}
		Set<Integer> userIds=new HashSet<Integer>();
		userIds.add(entity.getUserId());
		BaseClientResult<Map<Integer, UserSimple>> userMapResult= userRemoteService.getUserMapByIds(userIds);
		return CrmWorkChangeUtils.getWorkCommentModel(entity,BaseClientResult.getResultData(userMapResult));
	}
	
	
}
